package com.oig.sys.query.support;


import com.oig.common.exception.BadRequestException;
import com.oig.sys.query.support.module.FieldExpression;
import com.oig.sys.query.support.module.QueryExpression;
import com.oig.sys.query.support.module.SortExpression;
import com.oig.sys.query.support.module.TableExpression;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


/**
 * 查询参数转sql
 */
@Component
public class DefaultQuerySqlConvert implements QuerySqlConvert {



    @Override
    public String limitSqlCovert(List<Integer> page) {
        if (page==null||page.size()<2){
            return "";
        }
        return String.format(" limit %d offset %d;", page.get(1), page.get(0));
    }

    @Override
    public String orderSqlCovert(QueryExpression queryExpression, Map<String, String> sort) {
        if (sort==null || sort.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(order_by);
        for (String sk : sort.keySet()) {
            String tableFieldName = queryExpression.getTableField(sk);
            if (tableFieldName==null){
                throw new BadRequestException(String.format("sort param :%s not allow!", sk));
            }
            sb.append(String.format(" %s %s,", tableFieldName, sort.get(sk)));
        }
        String str =  sb.toString() ;
        return  str.substring(0,str.length()-1) ;
    }


    @Override
    public String defaultOrderSqlCovert(List<SortExpression> orderBy) {
        if (orderBy==null || orderBy.isEmpty()){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(order_by);
        for (SortExpression se : orderBy) {
            if (se.getValue()==null || se.getValue().isEmpty()){
                sb.append(String.format(" %s %s,", se.getField(), se.getSort()));
            } else {
                StringBuilder sortBuilder = new StringBuilder();
                for (String sNum : se.getValue()){
                    sortBuilder.append(String.format("'%s',", sNum));
                }
                String sortValues = sortBuilder.toString();
                sb.append(String.format(" FIELD(%s, %s) %s,", se.getField(), sortValues.substring(0, sortValues.length()-1), se.getSort()));
            }
        }
        String str =  sb.toString() ;
        return  str.substring(0, str.length()-1) ;
    }

    @Override
    public String groupSqlCovert(List<String> groupBy) {
        if (groupBy==null || groupBy.isEmpty()){
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(group_by);
        for (String sk : groupBy) {
            sb.append(String.format(" %s,", sk));
        }
        String str =  sb.toString() ;
        return  str.substring(0,str.length()-1) ;
    }

    /**
     * from 语句块
     */
    @Override
    public String fromSqlCovert(QueryExpression queryExpression) {
        StringBuilder builder = new StringBuilder();
        for (TableExpression table : queryExpression.getTables()){
            if ("master".equals(table.getJoin())){
                builder.append(String.format(" from %s as %s ", table.getField(), table.getRename())) ;
            }
        }
        //拼接左连表，先支持左联
        for (TableExpression table : queryExpression.getTables()){
            //String.format(" left join %s as %s on %s ", t.field, t.reName, t.on)
            //{"field": "warehouse", "rename": "t2", "join": "left join", "on": "t1.warehouse_id = t2.id"}
            if (!"master".equals(table.getJoin())){
                builder.append(String.format(" %s %s as %s on %s", table.getJoin(), table.getField(), table.getRename(), table.getOn())) ;
            }
        }
        return builder.toString();
    }


    /**
     * select 语句块
     */
    @Override
    public String selectSqlCovert(QueryExpression queryExpression) {
        StringBuilder builder = new StringBuilder();
        builder.append(select) ;
        int i=0;
        for (FieldExpression field : queryExpression.getFields()){
            //{"field": "t1.create_time", "rename": "create_time", "cnname": "create_time", "options": {"dataType": "int"}},
            if (i>0){
                builder.append(", ");
            }
            builder.append(String.format(" %s as %s ",field.getField(), field.getRename()));
            i++;
        }
        builder.append(fromSqlCovert(queryExpression)) ;
        return builder.toString();
    }


    /**
     * select count(*) 语句块
     */
    @Override
    public String countSqlCovert(QueryExpression queryExpression) {
        StringBuilder builder = new StringBuilder();
        builder.append(select) ;
        if (queryExpression.getGroupBy()!=null&&!queryExpression.getGroupBy().isEmpty()){
            builder.append(String.format(" count(distinct %s)", queryExpression.getGroupBy().get(0)));
        } else {
            builder.append(" count(*) ");
        }
        builder.append(fromSqlCovert(queryExpression));
        return builder.toString();
    }
}
